/**
 * Copyright (c) 2014, Jason Gardner
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package freecake.tenthousand;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import freecake.tenthousand.states.*;
import freecake.tenthousand.util.ScoringUtilities;


public class TenThousand implements InputListener {

    public static int playerScore = 0;
    public static int cpuScore = 0;
    public static boolean playerTurn = true;

    /* TODO
        * Randomly pick who goes first
        * Finish updating rules pages with missing rules
        * Clear screen on Windoze
    */

    public enum GameState {
                            Welcome,
                            RulesPage1,
                            RulesPage2,
                            RulesPage3,
                            TurnStart,
                            AfterHold,
                            AfterRoll,
                            AfterStay,
                            AfterBust,
                            BadHold,
                            ChangeUser,
                            GameOver
                            };

    private Console console;
    private GameState state;
    private boolean prevPlayerOut = false;

    private final List<TenThousandState> stateHandlers = Collections.unmodifiableList(Arrays.asList(
                                                                                            (new WelcomeState()),
                                                                                            (new RulesPageState()),
                                                                                            (new PlayerTurnState()),
                                                                                            (new CpuTurnState()),
                                                                                            (new GameOverState())
                                                                                    ));

    public final void run() {
        console = new Console(this);
        console.start();
        transitionTo(GameState.Welcome);
    }

    public final void handleInput(int charCode) {
        if (charCode == 81 || charCode == 113) {
            clearScreen();
            System.exit(0);
        }
        for (TenThousandState handler : stateHandlers) {
            GameState newState = handler.handleUserInput(state, charCode);
            if (newState != null) {
                transitionTo(newState);
                return;
            }
        }
    }

    private final void transitionTo(GameState newState) {
        if (newState == GameState.ChangeUser) {
            if (prevPlayerOut) {
                newState = GameState.GameOver;
            } else {
                if (playerTurn && playerScore >= ScoringUtilities.GAME_OVER_THRESHOLD ||
                    !playerTurn && cpuScore >= ScoringUtilities.GAME_OVER_THRESHOLD) {
                    prevPlayerOut = true;
                }
                playerTurn = !playerTurn;
                newState = GameState.TurnStart;
            }
        }
        state = newState;
        clearScreen();
        printHeader();
        for (TenThousandState handler : stateHandlers) {
            boolean result = handler.handleStateTransition(state, new TransitionCallback() {
                                                                        public void transitionToGameState(
                                                                                TenThousand.GameState newState) {
                                                                            transitionTo(newState);
                                                                        }
                                                                    });
            if (result == true) {
                break;
            }
        }
    }

    private final void clearScreen() {
        if (!System.getProperty("os.name").toLowerCase().contains("windows")) {
            String ANSI_CSI = "\u001b[";
            System.out.print(ANSI_CSI + 2 + "J");
            System.out.flush();
            System.out.print(ANSI_CSI + "1;1H");
            System.out.flush();
        }
    }

    private final void printHeader() {
        System.out.println("**********************************************************************");
        System.out.println("*************************  10,000 Dice Game  *************************");
        System.out.println("**********************************************************************");
    }

    public static void main(String[] args) {
        TenThousand tt = new TenThousand();
        tt.run();
    }

}
